package com.example.demo.handler;

import com.example.demo.annotations.NeedLogin;
import com.example.demo.utils.JWTUtil;
import com.example.demo.utils.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

@Component
public class LoginHandler implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("=============进入拦截器============");
        if (!(handler instanceof  HandlerMethod)){
            System.out.println("=============退出拦截器==========");
            return  true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        method.setAccessible(true);
        if (!method.isAnnotationPresent(NeedLogin.class)){
            System.out.println("=============退出拦截器==========");
            return true;
        }else{
            NeedLogin needLogin = method.getAnnotation(NeedLogin.class);
            String token = request.getHeader("token");
            System.out.println("接收token["+token+"]");
            if (token==null||token.equals("")){
                System.out.println("=============退出拦截器==========");
                throw new RuntimeException("没有有效token");
            }else{
                String role = needLogin.role();
                Map<String, String> map = JWTUtil.analyzeToken(token);
                String tokenRole=map.get("role");
                String tokenUserName=map.get("username");
                System.out.println("token解析role:"+tokenRole);
                if (StringUtils.isBlank(tokenRole)||StringUtils.isBlank(tokenUserName)){
                    System.out.println("=============退出拦截器==========");
                    throw new RuntimeException("token["+token+"]无效");
                }
                if (role.equals("admin")&&!tokenRole.equals("admin")){
                    System.out.println("=============退出拦截器==========");
                        throw new RuntimeException("用户["+tokenUserName+"]没有本操作的权限");
                }
                if (role.equals("hr")&&!tokenRole.equals("hr")){
                    System.out.println("=============退出拦截器==========");
                    throw new RuntimeException("用户["+tokenUserName+"]没有本操作的权限");
                }
                SecurityUtil.securityLogin(tokenUserName,tokenRole);
                System.out.println("=============退出拦截器==========");
                return true;
            }
        }
    }
}
